package dk.logs;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import dk.beans.Requestlog;
import dk.mapper.RequestLogMapper;

@Aspect
@Component

public class AopLogger {
	@Value("${server.port}")
	Integer port;
	@Value("${spring.application.name}")
	String name;
	@Autowired
	RequestLogMapper requestlogservice;
	@Pointcut("execution(public * dk.controller.*.*(..))")
	public void cms() {
	}

	@Before(value = "cms()")
	@Transactional(propagation=Propagation.REQUIRES_NEW) 
	public void deBefore(JoinPoint joinPoint) throws Exception {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		
		Map map = request.getParameterMap();
		
		String params = JSON.toJSONString(map);

		System.out.println(params);
		StringBuffer requestURL = request.getRequestURL();
		System.out.println(requestURL);
		String[] split = requestURL.toString().split("/");
		//接收到请求 准备放到数据库中
		Requestlog requestlog = new Requestlog();
		requestlog.setRequestName(split[3]);
		requestlog.setRequestPort(port);
		requestlog.setServerName(name);
		requestlog.setRequestParams(params);
		
		requestlogservice.insert(requestlog);
	}
}
